﻿using Newtonsoft.Json;
using System.Text.Json.Serialization;

namespace XieCan.Core
{
  /// <summary>
  /// 操作结果类
  /// </summary>
  /// <typeparam name="T">操作结果的数据类型</typeparam>
  public sealed class OperateResult<T>
  {
    private OperateResult()
    {
    }

    /// <summary>
    /// 操作标识
    /// </summary>
    public int Code { get; private set; } = 200;

    /// <summary>
    /// 操作结果
    /// </summary>
    public T? Data { get; private set; } = default;

    /// <summary>
    /// 结果说明
    /// </summary>
    public string Message { get; private set; } = "";

    /// <summary>
    /// 操作成功
    /// </summary>
    /// <param name="data">操作结果</param>
    /// <param name="message">操作说明</param>
    /// <param name="code">操作标识</param>
    /// <returns></returns>
    public static OperateResult<T> Succeeded(T data, string message = "", int code = 200) => new()
    {
      Code = code,
      Data = data,
      Message = message
    };

    /// <summary>
    /// 操作失败
    /// </summary>
    /// <param name="message">操作说明</param>
    /// <param name="code">操作标识</param>
    /// <returns></returns>
    public static OperateResult<T> Failed(string message, int code = 0)
    {
      return new OperateResult<T>()
      {
        Code = code,
        Data = default,
        Message = message
      };
    }

    /// <summary>
    /// 操作异常
    /// </summary>
    /// <param name="exception">内部异常</param>
    /// <param name="code">操作标识</param>
    /// <returns></returns>
    public static OperateResult<T> Failed(Exception exception, int code = 0) => new()
    {
      Code = code,
      Data = default,
      Message = exception.DepthException().Message
    };
  }
}
